import { FC, useEffect, useRef, useState } from "react"
import Taro from '@tarojs/taro'
import camera from '../../resource/camera.png'
import style from './style.less'

const grey = {
  // borderColor: '#e6e6e6',
  border: "1px solid #e6e6e6",
  color: '#CCCCCC',
};

const orange = {
  // borderColor: '#f5a500',
  border: "1px solid #f5a500",
  color: '#f5a500',
};

const Auth: FC = () => {
  const [url, setUrl] = useState('')
  const [url2, setUrl2] = useState('')
  const [color, setColor] = useState<string>('orange');
  const [number, setNumber] = useState<number>(60);
  const [isShow, setIsShow] = useState(false)
  const timer = useRef<number>(0);
  const mounted = useRef<boolean>(true);
  const name = useRef<HTMLInputElement>(null)
  const phone = useRef<HTMLInputElement>(null)
  const card = useRef<HTMLInputElement>(null)
  const time = useRef<HTMLInputElement>(null)
  const yzm = useRef<HTMLInputElement>(null)

  useEffect(() => {
    return () => {
      mounted.current = false;
      clearInterval(timer.current);
    }
  }, [])

  const chooseImg = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const tempFilePath = res.tempFilePaths[0]
        setUrl(tempFilePath)
        if (url2) {
          Taro.request({
            url: 'http://10.190.84.29:9527/fta-usercenter/auth/ocr',
            method: 'POST',
            success: (data) => {
              console.log(data);

              Taro.showLoading()
              setTimeout(() => {
                Taro.hideLoading()
                name.current!.value = data.data.data.name
                card.current!.value = data.data.data.identityNo
                time.current!.value = data.data.data.validityTime
                setIsShow(true)
              }, 1500)
            },
            fail: () => {
              Taro.hideLoading()
              Taro.showToast({
                title: '识别失败，请重新上传',
                icon: 'none',
                duration: 1500
              })
            }
          })
        }
      }
    })
  }

  const chooseImg2 = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const tempFilePath = res.tempFilePaths[0]
        setUrl2(tempFilePath)
        if (url) {
          Taro.request({
            url: 'http://10.190.84.29:9527/fta-usercenter/auth/ocr',
            method: 'POST',
            success: (data) => {
              Taro.showLoading()
              setTimeout(() => {
                Taro.hideLoading()
                name.current!.value = data.data.data.name
                card.current!.value = data.data.data.identityNo
                time.current!.value = data.data.data.validityTime
                setIsShow(true)
              }, 1500)
            },
            fail: () => {
              Taro.hideLoading()
              Taro.showToast({
                title: '识别失败，请重新上传',
                icon: 'none',
                duration: 1500
              })
            }
          })
        }
      }
    })
  }

  const submit = () => {
    if (name.current?.value && phone.current?.value && card.current?.value && yzm.current?.value) {
      Taro.showLoading({
        title: '加载中',
      })
      Taro.request({
        url: 'http://10.190.84.29:9527/fta-usercenter/auth/verifyCode',
        method: 'POST',
        data: JSON.stringify({
          phoneNumber: phone.current.value,
          verifyCode: yzm.current.value
        }),
        success: (data) => {
          if (data.data.result) {
            Taro.request({
              url: 'http://10.190.84.29:9527/fta-usercenter/auth/verify',
              method: 'POST',
              data: JSON.stringify({
                appType: 1, name: name.current?.value, identityNo: card.current?.value,
                telephone: phone.current?.value, token: Taro.getStorageSync('token')
              }),
              success: (data) => {
                console.log(data);
                if (data.data.errorMsg === '实名认证失败') {
                  Taro.hideLoading()
                  Taro.showToast({
                    title: '请勿重复认证',
                    icon: 'none',
                    duration: 1500
                  })
                } else {
                  Taro.setStorageSync('auth', data.data.data.isAuth)
                  Taro.hideLoading()
                  Taro.reLaunch({ url: '/packageA/success/index?title=审核结果&info=审核成功～' })
                }
              },
              fail: () => {
                Taro.hideLoading()
              }
            })
          } else {
            Taro.hideLoading()
            Taro.showToast({
              title: '验证码错误',
              icon: 'none',
              duration: 1500
            })
          }
        },
        fail: () => {
          Taro.hideLoading()
        }
      })

    } else {
      Taro.showToast({
        title: '请填写必要信息',
        icon: 'none',
        duration: 1500
      })
    }
  }

  const getCode = () => {
    if (phone.current?.value.length !== 11) {
      Taro.showToast({
        title: '请先填写正确的手机号',
        icon: 'none',
        duration: 1500
      })
      return
    }
    if (mounted.current) {
      setColor('grey');
      setNumber(59);
      timer.current = window.setInterval(() => {
        setNumber(oldVal => {
          if (oldVal <= 1) {
            clearInterval(timer.current);
            setNumber(60);
            setColor('orange');
          }
          return oldVal - 1;
        });
      }, 1000);
      Taro.request({
        url: 'http://10.190.84.29:9527/fta-usercenter/auth/sendVerifyCode',
        method: 'POST',
        data: JSON.stringify({
          phoneNumber: phone.current.value
        }),
        success: (data) => {
          console.log(data);

        },
        fail: (err) => {
          console.log(err);

        }
      })
    }
  }

  return (
    <div className={style.root}>
      <div className="tips">为了更好的为您服务，请填写真实有效的信息</div>
      <div className="cards">
        <div className="cards-title">身份信息</div>
        <div className="cards-up">上传身份证人像面</div>
        <div className="cards-down">上传身份证国徽面</div>
        <div className="cards-top" onClick={chooseImg}>
          {url && <img src={url} alt="" className="img1" />}
          <img src={camera} alt="" className="img2" />
        </div>
        <div className="cards-bottom" onClick={chooseImg2}>
          {url2 && <img src={url2} alt="" className="img1" />}
          <img src={camera} alt="" className="img2" />
        </div>
      </div>
      <div style={{ display: isShow ? "block" : "none" }}>
        <div className="info">
          <div>姓名</div>
          <input type="text" ref={name} placeholder="必填" />
        </div>
        <div className="info">
          <div>身份证号</div>
          <input type="text" ref={card} placeholder="必填" />
        </div>
        <div className="info">
          <div>有效期至</div>
          <input type="text" ref={time} placeholder="必填" />
        </div>
        <div className="info">
          <div>手机号</div>
          <input type="number" ref={phone} placeholder="必填" />
          <button
            type="button"
            style={color === 'orange' ? orange : grey}
            onClick={getCode}
            disabled={color === 'orange' ? undefined : true}
          >
            {number === 60 ? '获取验证码' : `${number}s后重发`}
          </button>
        </div>
        <div className="info">
          <div>验证码</div>
          <input type="number" ref={yzm} placeholder="必填" />
        </div>
      </div>
      <div className="submit" onClick={submit}>提交审核</div>
    </div>
  )
}

export default Auth